<?php

require_once("config.php");
require_once("Model/Kid.php");
require_once("Model/Archive.php");
require_once("Model/DB.php");




$request = array_merge($_GET,$_POST);

$upload_dir = realpath(dirname(__FILE__))."/".$request['path']."/";

	if (sizeof($_POST)||sizeof($_FILES))
	{		
		$error = "";
		$msg = "";
		$link = "";
		$fileElementName = 'image';
		$exts=explode(".",$_FILES['image']['name']);
		$count=sizeof($exts)-1;
		$ext=trim(strtolower($exts[$count]));
		
		
		if($ext!="gif"&&$ext!="jpeg"&&$ext!="jpg"&&$ext!="png"&&$ext!="wbmp"){
			$error ='Only Images file are allowed to upload';
		}else{
		if(!empty($_FILES[$fileElementName]['error']))
		{			
			switch($_FILES[$fileElementName]['error'])
			{
	
				case '1':
					$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
					break;
				case '2':
					$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
					break;
				case '3':
					$error = 'The uploaded file was only partially uploaded';
					break;
				case '4':
					$error = 'No file was uploaded.';
					break;
	
				case '6':
					$error = 'Missing a temporary folder';
					break;
				case '7':
					$error = 'Failed to write file to disk';
					break;
				case '8':
					$error = 'File upload stopped by extension';
					break;
				case '999':
				default:
					$error = 'No error code avaiable';
			}
		}elseif(empty($_FILES['image']['tmp_name']) || $_FILES['image']['tmp_name'] == 'none')
		{
			$error = 'No file was uploaded..';
		}
		elseif($_FILES['image']['size']>2048000){
			$error = 'Execeed the max file size 2MB';
		}else 
		{
			
			$v = $_FILES['image']['name'];
			$v = str_replace(" ",'',$v);
			$file_name = $date.'_'.basename($v);
			
			
			$upload_file = $upload_dir.$file_name;
			
			// Resize to fixed size
			move_uploaded_file($_FILES['image']['tmp_name'],$upload_file);
			
			// Add watermark
			$link = $request['path']."/".$file_name;
			// Close log file
			if($request['path']=='avatar'){
				Kid::avatar($request['id'],$file_name);
			}
			elseif($request['path']=='archive'){
				Archive::image($request['id'],$file_name);
			}
			
			
		}
		}
		
		echo "{error:'$error',link:'$link',}";
	}


